'''
Created on 16/giu/2013

@author: ROMAGNOLIC
'''
from datetime import datetime
import logging

import  serial

class Race:
    def __init__(self):
        logging.info('Init obj Race')
        self.out_file = open("mini4wdrace.txt","a")
        self.out_file.write('Nuovo run \n')
        self.lapnumber=0
        self.lastlane=""
        self.numcar=1
        self.laptime=[]
        self.lanetime=[]
        
    def __del__(self):
        logging.info('Destroy obj Race')
        self.out_file.close()
        
    def read(self, lane):
        
        # Antibounce
        if (self.lastlane<>lane):
            logging.info('Added time: %s to position: %s'% (datetime.now(),len(self.laptime)))
            self.laptime.append(datetime.now())
            self.lastlane=lane
        else:
            logging.info('Read antibounce on lane: %s'% lane)
            
 
    def getlapresult(self):
        for i in range(1,len(self.laptime)):
            tt=self.laptime[i]- self.laptime[i-1]
            self.lanetime.append(tt)
            self.out_file.write ('   Lap time at lap %s is %s\n'%(i,(tt)))
            self.out_file.flush()
            logging.info('   Lap time at lap %s is %s'%(i,( self.laptime[i]- self.laptime[i-1])))
                
    def getraceresult(self):
        for i in range(1,len(self.laptime),3):
            try:
                self.out_file.write ('   Lap race time is %s\n'%( self.laptime[i+3-1]- self.laptime[i-1]))
                self.out_file.flush()
                logging.info('   Lap race time is %s'%( self.laptime[i+3-1]- self.laptime[i-1]))
            except:
                logging.info ('   Finita gara')
    def getracecrono(self):
        for i in range(0,2):
            self.out_file.write ('   Crono for lane %s \n'%i+1)
            for j in range(0,len(self.lanetime),3):
                try:
                    self.out_file.write ('       Laptime is %s\n'%( self.lanetime[i+j]))
                    self.out_file.flush()
                    logging.info('   Laptime is %s'%(self.lanetime[i+j]))
                except:
                    logging.info ('   Finita gara')  


logging.basicConfig( level=logging.INFO)
logging.info("Start Race")
race=Race()
try:
    ser = serial.Serial(8, 9600, timeout=5)

    for i in range(0, 400):
        rl= ser.readline()[1:4]
        if rl=='001':
            race.read('lane1')
        if rl=='002':
            race.read('lane2')
        if rl=='003':
            race.read('lane3')
    ser.close()
except:
    logging.fatal('No serial port')
race.getlapresult()
race.getraceresult()
logging.info("End Race")